package com.rq.demo.controller;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;

import com.rq.base.BASE;
import com.rq.base.net.HTTP;
import com.rq.base.net.HttpThreadManager;
import com.rq.base.net.RequestType;
import com.rq.base.ui.BaseController;
import com.rq.base.ui.impl.OnClick;
import com.rq.base.util.AppUtils;
import com.rq.base.util.LOG;
import com.rq.demo.R;
import com.rq.demo.bean.TestBean;
import com.rq.demo.net.Constants;
import com.rq.demo.net.HttpManager;

import java.io.File;

import ecomm.lib_comm.permission.PermissionUtil;


public class NetController extends BaseController implements View.OnClickListener {


    @Override
    public int getLayoutId() {
        return R.layout.act_net;
    }

    @Override
    public void onViewCreated(Bundle savedInstanceState) {
        super.onViewCreated(savedInstanceState);

    }

    @Override
    @OnClick({R.id.btn_get, R.id.btn_post, R.id.btn_download})
    public void onClick(View v) {
        if (v.getId() == R.id.btn_get) {
            HttpManager.test(this);
        } else if (v.getId() == R.id.btn_post) {
            HttpManager.testPost(this);
        } else if (v.getId() == R.id.btn_download) {
//            DownloadUtil.setSaveDir(BASE.getBaseDir());

//            HTTP.get().post(Constants.NET_CODE.testPOST, params, BaseBean.class, view);
            PermissionUtil.selectLocalFile(getActivity(), new PermissionUtil.OnPermissionListener() {
                @Override
                public void onPermissionOk() {
                    HttpManager.testDownload(new HttpThreadManager.DownListener() {
                        @Override
                        public void onProgress(int progress, int all) {
                            setData2View(v, ((((progress/1024) + "/" + (all /1024)))));// + "%"
                        }

                        @Override
                        public void onCompleted(File file) {
                            setData2View(v, "下载完成");
                            LOG.e("NetController", "onCompleted:" + file.getPath());
                            AppUtils.installApp(getContext(), file);
                        }

                        @Override
                        public void onError(String msg) {

                        }
                    });
//                    Downloader.getInstance().startDownload(getActivity(), url).autoInstall(getActivity());
                }
            });
        }
    }

    @Override
    public <T> void onResponseSucceed(@NonNull RequestType type, T data) {
        super.onResponseSucceed(type, data);
        if (type.is(Constants.NET_CODE.test)) {
            TestBean bean = (TestBean) data;
            LOG.bean("NetController", bean.getTotal());
        } else if (type.is(Constants.NET_CODE.testPOST)) {
            LOG.bean("NetController.post", data);
        }
    }
}
